<template>
    <el-upload
        class="avatar-uploader"
        action="api/admin/common/upload"
        :auto-upload="true"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        <!-- <div class="avatar-msg">修改图片</div> -->
    </el-upload>
</template>

<script>
export default {
    // 父给子传参
    props:['imageUrl'],
    data() {
        return {
            // imageUrl:''
        }
    },
    methods:{
        //图片上传
      handleAvatarSuccess(res, file) {
        // console.log(this.imageUrl)
        this.imageUrl = res.data;
        console.log('组件:'+this.imageUrl)
        //传值给父组件
        this.$emit('imageUrl2',this.imageUrl)
        
      },
      beforeAvatarUpload(file) {
        console.log("beforeUpload",file)
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        // const isJPG = file.type === 'image/jpeg';
        const isLt20M = file.size / 1024 / 1024 < 20;

        if (!isJPG&&!isPNG) {
          this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
        }
        if (!isLt20M) {
          this.$message.error('上传头像图片大小不能超过 20MB!');
        }
        console.log((isJPG || isPNG) && isLt20M)
        return (isJPG || isPNG) && isLt20M;
      },
      base64ImgtoFile (dataurl, filename = 'file') {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },
    }
}
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
    border-radius: 5px;
  }


</style>